package com.dong.demo222.controller;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import com.dong.demo222.domin.LoginBody;
import com.dong.demo222.domin.SysMenu;
import com.dong.demo222.domin.SysUser;
import com.dong.demo222.model.AjaxResult;
import com.dong.demo222.utils.JwtTokenUtil;
import com.dong.demo222.utils.SecurityUtils;
import com.fasterxml.jackson.annotation.JsonInclude;
import jakarta.annotation.security.PermitAll;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class loginController {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @RequestMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody){

        String username = loginBody.getUsername();
        String password = loginBody.getPassword();

        String token = null;
        // 密码需要客户端加密后传递
        try{
            // 根据用户名从数据库中获取用户信息
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            // 进行密码匹配
            if (!passwordEncoder.matches(password,userDetails.getPassword())){
                AjaxResult.error("500","密码错误");
            }


            // 封装用户信息（由于使用 JWT 进行验证，这里不需要凭证）
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
            // 将用户信息存储到 Security 上下文中，以便于 Security 进行权限验证
            SecurityContextHolder.getContext().setAuthentication(authentication);
            // 生成 token
            token = jwtTokenUtil.generateToken(userDetails);

        }catch (AuthenticationException e){
            throw new RuntimeException("登录异常:{}"+e.getMessage());
        }
        return AjaxResult.success().put("token", token);

    }

    @PostMapping("/logout")
    public AjaxResult logout()
    {
        return AjaxResult.success();
    }

}
